<template>
        <div class="common-layout">

            <div class="one-aside">
                <div style="width: 250px;display: flex;flex-direction: column;place-items:center;align-items:center">
                    <div class="step">Step I: Explore events</div>
                    <div class="Events">Events added:</div>
               
                    <div style="display: flex;flex-direction: column;height: 100%;padding-bottom: 170px;">
                        <el-scrollbar class="eventbox-scroll" >
                            <div style="height: 100%;" >
                        <div class="event-item-one" v-for="item, index in store.state.events">
                            <div class="event-item-one-content">

                                <img style="width: 15px;height: 15px;" src="../../assets/locate.png"></img>
                                <div> {{ item.name }}</div>
                               
                            </div>
                            <div @click="deleteEvent(item)">
                                <svg t="1724432282202" class="icon" viewBox="0 0 1024 1024" version="1.1"
                                    xmlns="http://www.w3.org/2000/svg" p-id="4259" width="200" height="200">
                                    <path
                                        d="M800 832c-8 0-16-3.2-22.4-9.6l-576-576c-12.8-12.8-12.8-32 0-44.8 12.8-12.8 32-12.8 44.8 0l576 576c12.8 12.8 12.8 32 0 44.8-6.4 6.4-14.4 9.6-22.4 9.6z"
                                        fill="#333333" p-id="4260"></path>
                                    <path
                                        d="M224 832c-8 0-16-3.2-22.4-9.6-12.8-12.8-12.8-32 0-44.8l576-576c12.8-12.8 32-12.8 44.8 0 12.8 12.8 12.8 32 0 44.8l-576 576c-6.4 6.4-14.4 9.6-22.4 9.6z"
                                        fill="#333333" p-id="4261"></path>
                                </svg>
                            </div>
                        </div>
                    </div>
                    </el-scrollbar>
                    </div>


                    <div class="bottom-btn-one" >
                    <el-button style="background-color: #ff9239;width: 160px;margin-bottom: 15px;" type="danger"
                        @click="setpTwo">Next Step</el-button>
                    <el-button style="background-color: #a1a1a1;width: 160px;" type="info"
                        @click="Discard">Close</el-button>
                    </div>
                </div>

            </div>

            <scenics @openDetail="openDetail">
            </scenics>

           
            <el-dialog custom-class="no-header-dialog" v-model="dialogTableVisible" width="700" :show-close="false"
            destroy-on-close   style="border-radius: 15px;padding: 0px;">

                <scenics-detail :scenicEntity="detailData"></scenics-detail>
            </el-dialog>


            <el-dialog align-center v-model="disCardDialogVisible" width="500" center :showClose="false" style="border-radius: 15px;"
                class="confirmDialog">
                <span style="display: flex;justify-content: center;font-size: large;color: #000;">Are you sure to discard
                    the plan created?</span>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button class="cancel-btn" @click="disCardDialogVisible = false">Cancel</el-button>
                        <el-button class="confirm-btn" type="primary" @click="confirmDisCard">
                            Confirm
                        </el-button>
                    </div>
                </template>
            </el-dialog>
        </div>
       
</template>
<script lang="ts" setup>
import { ElMessage, ElMessageBox } from 'element-plus'

import { onMounted, onBeforeUnmount, onUnmounted } from 'vue';
import draggable from "vuedraggable";
import Cookies from 'js-cookie';
import { useRoute, useRouter } from 'vue-router';
import cache from "@/plugins/cache";
import { guid, addUserguid } from '@/api/index';
import { ref } from 'vue'
import { ElScrollbar } from 'element-plus'
import scenics from '@/components/Map/scenics.vue';
import scenicsDetail from '@/components/Map/scenicsDetail.vue';
// import Map from '@/components/Map/index.vue';
const router = useRoute();
const routers = useRouter();
import { useStore } from 'vuex';
const store = useStore();
const height = ref('')
store.commit('setGuidEdit'); // 通过 dispatch 触发 mutation

const windowHeight = ref(window.innerHeight);
const updateButtonVisibility = () => {
    height.value = windowHeight.value - 86
    console.log(height.value)
};
const disCardDialogVisible = ref(false)
const dialogTableVisible = ref(false);
const detailData = ref({});
const events = ref([]);
const item = ref("");
const data = ref({});
const plans = ref([]);
const doubleClickZoom = ref(true);

const map = ref()
// 类型定义
const scroll = ref<InstanceType<typeof ElScrollbar> | null>(null);
const control = ref({
    scale: {},
    zoom: {
        position: 'bottomRight',
    },
})

function openDetail(params) {
    dialogTableVisible.value = true;
    detailData.value = params;
}

function Discard() {
    disCardDialogVisible.value = true;
}
function confirmDisCard() {
    routers.push({
        path: '/'
    })
}
function deleteEvent(item) {
    if (item.checked) {
        item.checked = false
        store.commit('delEvents', item); // 通过 dispatch 触发 mutation 
    }
}
function setpTwo() {
    //events保存在sessionn
     store.commit('saveAddEventsCooike');
     if (router.query.id) {
        routers.push({
        path: '/stepTwo',
        query:{
            id:router.query.id
        }
    })
    }else{
        routers.push({
        path: '/stepTwo'
    })
    }
  
}
//... ...
onMounted(() => {
    store.commit('setGuidEdit'); // 通过 dispatch 触发 mutation
    updateButtonVisibility();
    window.addEventListener('resize', updateButtonVisibility);
    if (router.query.id) {
        item.value = router.query.id
        getGuid();
    }
    if (router.query.date) {

        console.log(router.query.date)
        const Dates = getDatesBetween(router.query.date[0], router.query.date[1])
        console.log(Dates)
        for (let index = 0; index < Dates.length; index++) {
            let date = Dates[index];
            let obj = {
                date: date,
                name: index + 1,
                title: "第" + (index + 1) + "天"
            }
            plans.value.push(obj)

        }
    }
    if ( cache.session.getJSON('events')) {
            if ( cache.session.getJSON('events').length > 0) {
                events.value = cache.session.getJSON('events')
                store.commit('saveEventsAdded',events.value);
            }
        }
})
// 在组件卸载时移除 ResizeObserver 监听
onUnmounted(() => {
    store.commit('setFalseGuidEdit');
    window.removeEventListener('resize', updateButtonVisibility);
});
onBeforeUnmount(() => {
    console.log('组件即将卸载');
    map.value?.destroy();
    setCookie()
    // 进行必要的清理操作，比如移除事件监听器
});


function del(index, params) {
    const element = plans.value[index].content
    for (let i = element.length - 1; i >= 0; i--) {
        const el = element[i];
        if (el.image === params.image) {
            element.splice(i, 1);
        }
    }
    plans.value[index].content = element

}

function setTitle() {

    for (let index = 0; index < plans.value.length; index++) {
        const element = plans.value[index];
        for (let i = 0; i < element.content.length; i++) {
            const el = element.content[i];

            if (i == 0) {

                el['titlename'] = "DAY " + element.name + "-" + formatDate(element.date)
            }
            // console.log(i)
            if (i > 0) {
                el['titlename'] = "Depart from " + element.content[i - 1].name
                el['bustime'] = element.content[i - 1].endTime + " - " + element.content[i].startTime
            }
        }
    }
}


function select(index, params) {
    const element = plans.value[index].content
    for (let index = 0; index < element.length; index++) {
        const el = element[index];
        if (el.image == params.image) {
            if (el.checkBox) {
                el.checkBox = false
            } else {
                el['checkBox'] = true
            }
        }
    }
    plans.value[index].content = element
}

//拖拽开始的事件
const onStart = () => {
    console.log("开始拖拽");
};

//拖拽结束的事件
const onEnd = () => {
    console.log("结束拖拽");
    console.log(plans.value)
    setTitle();

};

async function setCookie() {
    // Cookies.set(plans.value.id+'-plans',JSON.stringify(plans.value))
    data.value.plans = plans.value
    // addUserGuid(data.value).then(res => {

    // })
}


const count = ref(0)
const value = ref(3.7)


const load = () => {
    count.value += 2
}


function getGuid() {
    guid({ id: item.value }).then(res => {
        data.value = res.data
        plans.value = res.data.plans
        setTitle()

    })
}


function formatDate(string) {
    const date = new Date(string);
    const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];

    const day = date.getDate();
    const month = months[date.getMonth()];
    const weekday = days[date.getDay()];

    return `${day} ${month} ${weekday}`;
}


function scrollset(index) {


    let l = 0;
    for (let i = 0; i < index; i++) {
        const element = plans.value[i]
        console.log(element.content.length)
        l = l + element.content.length
    }

    scroll.value.setScrollTop(l * 300)

}




function calculateDaysBetweenDates(startDateStr, endDateStr) {
    // 将日期字符串解析为 Date 对象
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);

    // 计算两个日期之间的差值（以毫秒为单位）
    const diffInMillis = endDate - startDate;

    // 将毫秒转换为天数
    const diffInDays = Math.ceil(diffInMillis / (1000 * 60 * 60 * 24));

    return diffInDays;
}


function getDatesBetween(startDateStr, endDateStr) {
    // 将日期字符串解析为 Date 对象
    const startDate = new Date(startDateStr);
    const endDate = new Date(endDateStr);

    // 结果数组
    const dates = [];

    // 当前日期从起始日期开始
    let currentDate = new Date(startDate);

    // 循环直到当前日期超过结束日期
    while (currentDate <= endDate) {
        // 将当前日期格式化为字符串并添加到结果数组
        dates.push(new Date(currentDate).toISOString().split('T')[0]);

        // 将当前日期增加一天
        currentDate.setDate(currentDate.getDate() + 1);
    }

    return dates;
}

</script>
<style scoped>
/* 确认框 start*/
.cancel-btn {
    background-color: #cacaca;
    border-color: #c9c9c9;
    margin-right: 65px;
    color: #000;
    width: 100px;
}
.cancel-btn:hover {
    background-color: #9a9a9a;
    border-color: #9a9a9a;
    color: #000;
}
.cancel-btn:active{
    background-color: #9a9a9a;
    border-color: #9a9a9a;
    color: #000;
}
.confirm-btn {
    background-color: #ff8800;
    border-color: #ff8800;
    color: #000;
    width: 100px;
}
.confirm-btn:hover {
    background-color: #ffa33a;
    border-color: #ffa33a;
    color: #000;
}
.confirm-btn:active {
    background-color: #ffa33a;
    border-color: #ffa33a;
    color: #000;
}
/* 确认框 end*/

.el-dialog__header {
    padding-bottom: 0px;
}

.common-layout {
    height: calc(100vh - 88px); /* 高度为视口高度减去头部高度 */
    display: flex;
    /* 高度为视口高度减去头部高度 */
    position: fixed;
    width: 100%;
    flex: 1;
    min-height: 440px;
    /* height: 100vh; */
}


.one-aside {

    width: 250px;

    border-top: 1px solid #ebebeb;
    border-right: 1px solid #ebebeb;
    display: flex;

    justify-content: center;
    padding-top: 10px;

 
}

.one-main {
    /* flex: 1;  */
    background-color: #fff;
    /* 背景颜色可根据需求调整 */
    padding: 20px;
    /* 内边距可根据需求调整 */
    overflow: auto;
    /* 使内容溢出时显示滚动条 */
    border-left: 1px solid #ebebeb;
    border-top: 1px solid #ebebeb;
    height: 100%;
}

.step {
    height: 25px;
    width: 200px;
    font-weight: bold;
    color: black;
}

.Events {
    height: 25px;
    width: 200px;
    font-size: 14px;
    color: #757575;
}

.event-item-one {
    width: 160px;
    display: flex;
    font-size: 13px;
    color: #000;
    background-color: #f1f1f1;
    padding: 5px;
    padding-left: 10px;
    line-height: 25px;
    margin-top: 5px;
    border-radius: 5px;
    justify-content: space-between;
    padding-right: 10px;
}

.event-item-one-content {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: flex;
    align-items: center;
    
}

/* .bottom-btn-one {

    position: fixed;
    bottom: 20px;
    display: flex;
    flex-flow: column nowrap;
    align-items: center;
} */

.bottom-btn-one {
    position: absolute;
    margin-top: 15px;
    /* margin-bottom: 15px; */
    bottom: 15px;
    display: grid;
    place-items: center;
    width: 250px;
    /* height: 126px; */
    /* background-color: #fff; */
    /* 背景颜色可以自定义 */
    /* padding: 10px; */
    /* display: flex; */
    /* flex-flow: column nowrap; */
    /* flex-wrap: wrap; */
    /* align-items: center;
    width: inherit; */
}

.el-button+.el-button {
    margin-left: 0;
}
.eventbox-scroll{
    height: 100%;
    min-height: 120px;
}
</style>